package com.yl.utils;

import cn.hutool.core.bean.BeanUtil;
import com.yl.entity.PermissionEntity;
import com.yl.vo.RouterVo;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 生成菜单树
 */
public class MenuTree {

    /**
     * 生成路由
     * @param menuList  菜单列表
     * @param pid  父菜单id
     * @return
     */
    public static List<RouterVo> makeRouter(List<PermissionEntity> menuList,Long pid){
        //创建集合保存路由列表
        List<RouterVo> routerVos = new ArrayList<>();
        //如果menuList菜单不为空，则使用菜单列表，否则创建集合对象
        //判断是否为空---为空等于true
        Optional.ofNullable(menuList).orElse(new ArrayList<PermissionEntity>())
                //筛选不为空菜单列表数据-且父id相等的数据
                .stream().filter(e -> e!= null && e.getParentId() == pid)
                .forEach(o ->{
                    RouterVo routerVo = new RouterVo();
                    routerVo.setName(o.getName()); //路由名称
                    routerVo.setPath(o.getPath()); //路由地址
                    //判断当前菜单是否一级菜单
                    if (o.getParentId() == 0){
                        routerVo.setComponent("Layout"); //一级菜单组件
                        routerVo.setAlwaysShow(true);  //显示路由
                    }else {
                        routerVo.setComponent(o.getUrl());  //具体的某一个组件
                        routerVo.setAlwaysShow(false);  //折叠路由菜单
                        routerVo.setComponent(o.getComponent());  //折叠路由菜单
                    }
                    //设置Mate信息
                    routerVo.setMeta(routerVo.new Meta(o.getLabel(), o.getIcon(), o.getCode().split(",")));
                    //递归生成路由
                    List<RouterVo> children = makeRouter(menuList, o.getId());  //生成子菜单
                    routerVo.setChildren(children); //设置子路由到路由对象中
                    routerVos.add(routerVo); //将路由添加到集合中去
                });
        return routerVos;
    }

    /**
     * 生成菜单树
     * @param menuList
     * @param pid
     * @return
     */

    public static List<PermissionEntity> makeMenuTree(List<PermissionEntity> menuList,Long pid){
        //创建集合保存菜单数据
        List<PermissionEntity> permissionEntityList = new ArrayList<>();
        //如果menuList菜单不为空，则使用菜单列表，否则创建集合对象
        Optional.ofNullable(menuList).orElse(new ArrayList<PermissionEntity>())
                .stream().filter(e -> e != null && e.getParentId() == pid)
                .forEach(o ->{
                    //创建权限菜单对象
                    PermissionEntity permissionEntity = new PermissionEntity();
                    //将原有的属性复制给菜单
                    BeanUtil.copyProperties(o,permissionEntity);
                    //获取每个对象的子菜单
                    List<PermissionEntity> children = makeMenuTree(menuList, pid);
                    //设置子菜单
                    permissionEntity.setChildren(children);
                    //菜单对象添加到集合
                    permissionEntityList.add(permissionEntity);
                });
        return permissionEntityList;
    }
}
